<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="../../../component/pear/css/pear.css" />
</head>

<body>
    <form class="layui-form" action="">
        <div class="mainBox">
            <div class="main-container">
                <div class="layui-form-item">
                    <label class="layui-form-label">账号</label>
                    <div class="layui-input-block">
                        <input type="text" id="account" maxlength="16" name="account" lay-verify="required"
                            placeholder="账号" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">姓名</label>
                    <div class="layui-input-block">
                        <input type="text" id="real_name" maxlength="16" name="real_name" lay-verify="required"
                            placeholder="姓名" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">密码</label>
                    <div class="layui-input-block">
                        <input type="text" id="password" maxlength="16" name="password" lay-verify="required"
                            placeholder="请输入密码" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label for="" class="layui-form-label">角色</label>
                    <div id="roleGroup" class="layui-input-block">
                        <div id="roleView"></div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- <div class="layui-form-item"> -->
        <div class="bottom">
            <div class="button-container">
                <button type="submit" class="layui-btn layui-btn-normal layui-btn-sm" lay-submit="" lay-filter="user-save">
                    <i class="layui-icon layui-icon-ok"></i>
                    提交
                </button>
                <button type="reset" class="layui-btn layui-btn-primary layui-btn-sm">
                    <i class="layui-icon layui-icon-refresh"></i>
                    重置
                </button>
            </div>
        </div>
    </form>



	<!-- LayUI模板 -->
    <script id="roleTempl" type="text/html">
        {{#  layui.each(d.list, function(index, item){ }}
        <input type="checkbox" name='roles' value={{ item.value }} title={{ item.title }}
            {{ item.checked ? 'checked' : '' }}>
        {{#  }); }}
        {{#  if(d.list.length === 0){ }}
        没有权限
        {{#  } }}
    </script>



    <script src="../../../component/layui/layui.js"></script>
    <script src="../../../component/pear/pear.js"></script>
    <script src="../../../lms/base64.js"></script>
    <!-- <script src="../../lms/md5.js"></script> -->
    <script src="../../../lms/common.js"></script>
    <script src="../../../lms/config.js"></script>



    <script>
        //鹰：
        if(!checkLogin()) {
            location.href = lms_config.base_path + "/login.html";
        }


        
        layui.use(['form', 'jquery', 'laytpl', 'http', 'encrypt'], function () {
            let form = layui.form;
            let encrypt = layui.encrypt;
            let $ = layui.jquery;

            const laytpl = layui.laytpl;
            const http = layui.http;



            let method = 'POST';
            if (getQueryString('operation') === 'edit') {
                method = 'PUT';
            }


            //监听事件
            form.on('submit(user-save)', function (data) {

                if ($("[name=roles]:checked").length < 1) {
                    ///$(data.elem).next().attr("class", "layui-unselect layui-form-checkbox");
                    ///$(data.elem).prop("checked", false);
                    layer.msg('请至少选择一个角色！', { icon: 5 });
                    return false;
                }

                //手动获取roles（因为checkbox默认只能获取最后一个的值）
                data.field.roles = [];

                //checked表示选择 状态为选择 的组件
                $('[name=roles]:checked').each(function(i,item){    //选择器后遍历
                    //console.log($(item).val(), $(item).attr("value"), $(item).prop('value'),
                    //    $(item).attr('checked'), $(item).prop('checked'))
                    //console.log($(item).prop('checked'));
                    if($(item).prop('checked'))
                        data.field.roles.push($(item).attr('value'));
                });
                data.field.roles = data.field.roles.join(',');


                if(data.field.password)
                data.field.password = encrypt.md5(data.field.password);
                else
                    delete data.field.password;


                $.ajax({
                    url: lms_config.api_url + "/adminapi/v1/setting/User" + (method === 'PUT' ? '/' + getQueryString('id') : ''),
                    type: method,
                    headers: {Authorization: getUserInfo()["token"]},
                    contentType: 'application/json',
                    data: JSON.stringify(data.field),
                    dataType: 'json',

                    success: function (ret) {
                        if (ret && ret.code == 0) {
                            layer.msg(ret.msg, {
                                icon: 1,
                                time: 1000
                            }, function () {
                                parent.layer.close(parent.layer.getFrameIndex(window.name)); //关闭当前页
                                
								parent.refresh();
                                //parent.layui.table.reload("data-table");
                                ///top.location.reload();
                                ///parent.location.reload();
                            });
                            return false;
                        }
                        else {
                            layer.msg(ret.msg, {
                                icon: 2,
                                //icon: 5,
                                time: 1000
                            });
                            return false;
                        }
                    },
                    error: function (ret) {
                        console.error(ret);
                        alert("出错" + ret.status + "：" + ret.responseText);
                    }, //表示如果请求响应出现错误，会执行的回调函数
                });

                return false;
            });


            //获取用户信息并渲染
            function getUser(roleData) {

                /// 鹰：访问接口
                $.ajax({
                    url: lms_config.api_url + "/adminapi/v1/setting/User/" + getQueryString('id'), // 请求路径
                    type: "GET", //请求方式
                    headers: {Authorization: getUserInfo()["token"]},
                    contentType: 'application/json',
                    //data: data.field, //请求参数
                    dataType: 'json',

                    success: function (ret) {

                        if (ret.code !== 0) {
                            layer.msg(ret.msg, {
                                icon: 2,
                                //icon: 5,
                                time: 1000
                            }, function () {
                                //location.href = lms_config.base_path + "/index.html"
                            });
                            return;
                        }

                        if (ret.data.length !== 1) {
                            layer.msg("没有此用户或用户出错", {
                                icon: 2,
                                //icon: 5,
                                time: 1000
                            }, function () {
                                //location.href = lms_config.base_path + "/index.html"
                            });
                            return;
                        }

                        let user = ret.data[0];
                        let roleIds = user.roles.split(','); //role数组
                        for (let r of roleIds) { //遍历，将属于的用户组标记checked
                            if (roleData.obj[r]) roleData.obj[r].checked = true;
                        }
                        laytpl(roleTempl.innerHTML).render({
                            list: roleData.arr
                        }, function (html) {
                            document.getElementById('roleView').innerHTML = html;
                        });

                        $('#account').attr("value", user.account);
                        $('#account').prop("disabled", "true");
                        $('#real_name').attr("value", user.real_name);
                        $('#password').attr("lay-verify", "");
                        $('#password').attr("placeholder", "不修改则留空");

                        form.render();

                    }, //响应成功后的回调函数
                    error: function (ret) {
                        console.error(ret);
                        alert("出错" + ret.status + "：" + ret.responseText);
                    }, //表示如果请求响应出现错误，会执行的回调函数

                    contentType: 'application/x-www-form-urlencoded',
                    dataType: "json" //设置接受到的响应数据的格式
                });

            }


            /// 鹰：访问接口：角色
            $.ajax({
                url: lms_config.api_url + "/adminapi/v1/setting/Role", // 请求路径
                type: "GET", //请求方式
                headers: {Authorization: getUserInfo()["token"]},
                contentType: 'application/json',
                //data: data.field, //请求参数
                dataType: 'json',

                success: function (ret) {

                    if (ret.code !== 0) {
                        layer.msg(ret.msg, {
                            icon: 2,
                            //icon: 5,
                            time: 1000
                        }, function () {
                            //location.href = lms_config.base_path + "/index.html"
                        });
                        return;
                    }


                    //arr是数组用来显示，obj为了方便索引来checked
                    let roleData = {
                        arr: [],
                        obj: {}
                    };
                    for (let d of ret.data) {
                        let r = {
                            title: d.role_name,
                            value: d.id
                        };
                        roleData.arr.push(r);
                        roleData.obj[d.id] = r;
                    }

                    //如果是编辑
                    if (getQueryString('operation') === 'edit')
                        getUser(roleData);
                    else
                        laytpl(roleTempl.innerHTML).render({
                            list: roleData.arr
                        }, function (html) {
                            document.getElementById('roleView').innerHTML = html;
                            form.render();
                        });


                }, //响应成功后的回调函数
                error: function (ret) {
                    console.error(ret);
                    alert("出错" + ret.status + "：" + ret.responseText);
                }, //表示如果请求响应出现错误，会执行的回调函数

                contentType: 'application/x-www-form-urlencoded',
                dataType: "json" //设置接受到的响应数据的格式
            });

        });
    </script>
</body>

</html>